// pages/index/rank.js
const db = wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    list: [],
    rank: 0
  },
  zan: function(e){
    var index = e.currentTarget.dataset.index
    var zans = e.currentTarget.dataset.zans
    var list = this.data.list
    list[index].zans = zans + 1
    this.setData({
      list
    })
    const _ = db.command
    db.collection('userInfo').where({
      _openid: list[index]._openid
    }).update({
      data: {
        zans: _.inc(1),
      }
    })
  },
  goshare: function(){
    this.onShareAppMessage()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    
    var openid = wx.getStorageSync('openid')
    if(!openid){
      wx.redirectTo({
        url: '../index/welcome',
      })
      return false
    }
    //查询用户信息
    db.collection('userInfo').where({
      _openid: openid
    }).get({
      success: res => {
        that.setData({
          userInfo: res.data[0]
        })
        //查询排名
        var rank = ''
        db.collection('userInfo').orderBy('corrects','desc').get({
          success: res => {
            var list = res.data
            list.forEach(function(item,index){
              if(item._openid == that.data.userInfo._openid){
                rank = index
              }

            })
            if(rank == ''){
              rank = '20+'
            }else{
              rank = rank + 1 
            }
            
            that.setData({
              list,
              rank,
              nomore: true
            })
          }
        })
      }
    })
    
    
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '点击查看排行榜',
      path: 'pages/index/rank'
    }
  },
    /**
  * 分享到朋友圈
  */
 onShareTimeline: function(){
  return {
    title: '微笑题酷排行榜',
    imageUrl: '../../images/logo.png'
  }
}
})